#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <vector>
using namespace std;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void *SlaverCore(void *args)
{
    string name = static_cast<char *>(args);
    while (1)
    {
        pthread_mutex_lock(&gmutex);

        pthread_cond_wait(&gcond, &gmutex);

        cout << "当前被叫醒的线程是：" << name << endl;
        pthread_mutex_unlock(&gmutex);
    }
}

void *MasterCore(void *args)
{
    sleep(3);
    cout<<"master start...";
    string name = static_cast<char *>(args);
    while (1)
    {
        pthread_cond_signal(&gcond);
        cout << "master 唤醒一个线程..." << endl;
        sleep(1);
    }
}

void StarMaster(vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void *)"Master thread");
    if (n == 0)
    {
        cout << "create master success" << endl;
    }
    tidsptr->emplace_back(tid);
}

void StartSlaver(vector<pthread_t> *tidsptr, int threadnum = 3)
{
    for (int i = 0; i < threadnum; i++)
    {
        char *name = new char[64];
        snprintf(name, 64, "slacer-%d", i + 1);
        pthread_t tid;
        int n = pthread_create(&tid, nullptr, SlaverCore, name);
        if (n == 0)
        {
            cout << "create  success" << name << endl;
            tidsptr->emplace_back(tid);
        }
    }
}

void WaitThread(vector<pthread_t> &tids)
{
    for (auto &tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}
int main()
{
    vector<pthread_t> tids;
    StarMaster(&tids);
    StartSlaver(&tids, 5);
    WaitThread(tids);
    return 0;
}